'use strict';
const { verifyJwt, loginResponse } = require('auth-token')
exports.main = async (event, context) => {
  // 需登录才能访问
  const payload = verifyJwt(event.token)
  if (!payload) {
    return loginResponse()
  }
  const currentUid = payload._id
  
  // 数据库连接
  const dbJQL = uniCloud.databaseForJQL({event, context})
  dbJQL.setUser({ // 指定后续执行操作的用户信息，此虚拟用户将同时拥有传入的uid、role、permission
    uid: 'currentUid', // 用户id
    role: [], // 指定当前执行用户的角色为admin。如果只希望指定为admin身份，可以删除uid和permission字段
    permission: ["auth.uid == doc.user_id"] // 用户权限
  })
  const affairCollection = dbJQL.collection('ume-affair')
  const portionCollection = dbJQL.collection('affaire_portion')
  
	//event为客户端上传的参数
	console.log('event : ', event)
	switch (event.action) {
    case 'create':
      const createData = event.portion_data
      if (!createData.affair_id) {
        return {
          message: '添加错误!无AFFAIRID',
          _id: undefined
        }
      }
      const createRes =  await portionCollection.add(createData)
      if (createRes.id) {
        return {
          _id: createRes.id,
          message: '创建事务记录成功!'
        }
      } else {
        return {
          _id: undefined,
          message: createRes.errMsg
        }
      }
      break;
    case 'read':
      const affairId =  event.affair_id
      const affaireRes = await affairCollection.doc(affairId).field('affair_name,affair_color,is_store').get({getOne: true})
      if (!affaireRes.data) {
        return {
          message: '数据不存在!',
          data: [],
          affair_data: null
        }
      }
      const portionRes = await portionCollection.where(`affair_id=='${affairId}'`).orderBy('rec_date desc').get();
      // 统计查询
      const statMoneyRes = await portionCollection.where(`affair_id=='${affairId}'`).groupBy('group_name').groupField('sum(rec_money) as total_money').get();
      // console.log('statMoneyRes', statMoneyRes)
      return {
        message: '查询成功!',
        data: portionRes.data,
        affair_data: affaireRes.data,
        stat_data: statMoneyRes.data
      }
      break;
    case 'update':
      const updateRec = event.portion_data
      const upRes = await portionCollection.doc(updateRec._id).update(updateRec)
      return {
        message: '修改成功!',
        _id: updateRec._id
      }
      break;
    case 'delete':
      const deleteId = event._id
      await portionCollection.doc(deleteId).remove()
      return {
        error: false,
        message: '删除成功!'
      }
      break;
    case 'readOne':
      // 获取一条
      const readOneId = event._id
      const readOneRes = await portionCollection.doc(readOneId).get({getOne:true})
      return {
        message: '查询成功!',
        data: readOneRes.data
      }
      break;
    default:
      break;
  }
	//返回数据给客户端
	return event
};
